<?php
/**
 * @date 2012-4-24
 * @author GhostWei
 */
class controller_admin_catalog_category extends system_controller_action {
	
	private $user = null;
	private $referer = null;
	private $language = null;
	private $parent_id = null;
	public function init() {
		if($this->adminLogin()) {
			return;
		}
		$this->view->language = $this->language = $this->view->language();
		$this->view->user = $this->user = system_user::getInstance()->getRow();
		$this->referer = $this->getRequest()->getHeader('referer');
		$this->view->parent_id = $this->parent_id = intval($this->getRequest()->getParam('p'));
		
		$this->crumbs()
			->addPage(system_nav_page::create($this->language->load('Catalog'))->setRoute('catalog/index'))
			->addPage(system_nav_page::create($this->language->load('Category'))->setRoute('catalog/category/index'));
	}
	
	public function action_index() {
		$this->redirector()->gotoRouteAndExit('catalog/category/list');
		$this->render();
	}
	
	public function action_addnew() {
		$concept = new catalog_category_concept();
		if(!$concept->fetch(array('category.id = ?' => $this->parent_id))) {
			$this->view->parent_id = $this->parent_id = 0;
		}	
		$row = $concept->create();
		$row->setDisplayOrder(0);
		$row->setIsActive(1);
		$row->setParentId($this->parent_id);
		$row = $this->_saveRow($row);		
		$this->view->row = $row;
		$this->view->referer = $this->referer;
		$this->_navPage();
		$this->crumbs()->addPage(system_nav_page::create($this->language->load('New Category'))->setRoute('catalog/category/addnew'));
		$this->render('catalog/category/row.phtml');
	}

	public function action_edit() {
		$id = intval($this->getRequest()->getParam('id'));
		$concept = new catalog_category_concept();
		if(!($row = $concept->fetch(array('category.id = ?' => $id)))) {
			throw new catalog_exception("This category is not existing.", 404);
		}
		$row = $this->_saveRow($row);
		$this->view->row = $row;
		$this->view->referer = $this->referer;
		$this->_navPage($id);
		$this->crumbs()->addPage(system_nav_page::create($this->language->load('Edit'))->setRoute('catalog/category/edit')->setParams(array('id' => $id)));
		$this->render('catalog/category/row.phtml');
	}
	
	public function action_move() {
		$id = intval($this->getRequest()->getParam('id'));
		$concept = new catalog_category_concept();
		if(!($row = $concept->fetch(array('category.id = ?' => $id)))) {
			throw new catalog_exception("This category is not existing.", 404);
		}
		if($this->getRequest()->isPost()) {
			$this->referer = $this->getRequest()->getPost('referer');
			try {
				$to = trim($this->getRequest()->getPost('to'));
				$top = trim($this->getRequest()->getPost('top'));
				if($top) {
					$row->setParentId(0);
					$row->save();
				} else {
					if(!$to) {
						throw new supplier_exception("Please select a category you want to move to.");
					}
					$row->setParentId($to);
					$row->save();
				}
				$this->view->throwMessage = "Complete";
			} catch (Exception $e) {
				$this->view->throwException = $e;
			}
		}
		$this->view->row = $row;
		$this->view->referer = $this->referer;
		$this->_navPage($id);
		$this->crumbs()->addPage(system_nav_page::create($this->language->load('MoveTo'))->setRoute('catalog/category/move')->setParams(array('id' => $id)));
		$this->render();
	}
	
	private function _saveRow($row) {
		if(!$this->getRequest()->isPost()) {
			return $row;
		}
		$this->referer = $this->getRequest()->getPost('referer');
		$row->setParentId(intval($this->getRequest()->getPost('parent_id')));
		$row->setName(trim($this->getRequest()->getPost('name')));
		$row->setEname(trim($this->getRequest()->getPost('ename')));
		$row->setDisplayOrder(intval($this->getRequest()->getPost('display_order')));
		$row->setDescription($this->getRequest()->getPost('description'));
		$row->setIsActive(intval($this->getRequest()->getPost('is_active')) ? 1 : 0);
		try {
			if($this->getRequest()->getPost('delete')) {
				$row->delete();
			} else {
				if(!empty($_FILES["thumb"]['tmp_name'])) {
					common_media_config::$imageFilter = array('jpg', 'png', 'gif');
					$thumb = common_media_image::create($_FILES["thumb"]);
					if($thumb) {
						$row->setThumb($thumb->getMd5());
					}
					$thumb->save();
				}
				if($this->getRequest()->getPost('deleteImage')) {
					$row->setThumb('');
				}
				$row = $row->save();
			}
			$this->view->throwMessage = 'Complete';
		} catch (Exception $e) {
			$this->view->throwException = $e;
		}
		return $row;
	}

	public function action_list() {
		$concept = new catalog_category_concept();
		$list = $concept->fetchAll(array('category.parent_id = ?' => $this->parent_id), array('category.display_order ASC'));		
		$ids = $children = array();
		foreach($list as $row) {
			$ids[$row->getId()] = $row->getId();
		}
		if(!empty($ids)) {
			$qId = "'" . implode('\', \'', $ids) . "'";
			foreach(system_db::getAdapter()->query("SELECT a.`id`, (SELECT COUNT(*) FROM `catalog_category` AS `b` WHERE `b`.`parent_id` = `a`.`id`) AS `count` FROM `catalog_category` AS `a` WHERE `a`.`id` IN($qId)") as $row) {
				$children[$row['id']] = $row['count'];
			}
		}		
		$this->view->list = $list;
		$this->view->children = $children;
		$this->_navPage();
		$this->render();
	}
	
	private function _navPage($id = null) {
		$this->crumbs()->addPage(system_nav_page::create($this->language->load('List'))->setRoute('catalog/category/list'));
		if(!!($path = catalog_category::categoryPath(($id === null ? $this->parent_id : $id)))) {
			krsort($path);
			foreach($path AS $row) {
				$this->crumbs()->addPage(system_nav_page::create($row->getName())->setRoute('catalog/category/list')->setParams(array('p' => $row->getId())));
			}
		}
	}

}